package com.alibaba.citrus.cr.order.open.api.facade.service.handler;

import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.unified.inventory.contants.FeaturesKey;
import com.alibaba.cz.base.tool.FeatureUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crunifiedinventory.dto.response.AllocateOrderCreateResponse;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCreateRequest;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateOrderTypeEnum;
import com.epoch.app.mninventorycenter.model.dto.ScItemResponse;
import com.epoch.app.mninventorycenter.model.dto.TransferOrderCreateRequest;
import com.epoch.app.mninventorycenter.model.dto.TransferOrderCreateResponse;
import com.epoch.app.mninventorycenter.model.dto.WarehouseQueryResponse;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * 仓间调拨
 *
 * @author mingyang
 * @since 2024/01/05
 */
@Component
public class BetweenWarehouseHandler extends AbstractAllocateOrderCreateHandler {

    private Log log = Log.getLogger(BetweenWarehouseHandler.class);


    @Override
    public Boolean support(TransferOrderCreateRequest request) {
        return Objects.equals(AllocateOrderTypeEnum.BETWEEN_WAREHOUSE.getType(), request.getTransferOrderType());
    }

    @Override
    public TransferOrderCreateResponse handle(TransferOrderCreateRequest request, Map<String, ScItemResponse> scItemInfoMap, WarehouseQueryResponse receiveLogicWareId, WarehouseQueryResponse deliveryLogicWareId) {
        AllocateOrderCreateRequest allocateOrderCreateRequest = getAllocateOrderCreateRequest(request,scItemInfoMap, receiveLogicWareId, deliveryLogicWareId);
//        //这里做仓间调拨退单的额外逻辑
//        if (support(request) && Boolean.TRUE.toString().equals(request.getReturnFlag())){
//            Map<String, String> featuresMap = FeatureUtil.fromString(request.getBizFeatures());
//            if (featuresMap.containsKey(FeaturesKey.ORIGIN_TRANSFER_ORDER_CODE)){
//                //写入原调拨单号 原调拨单sap号
//                allocateOrderCreateRequest.setBizFeatures(request.getBizFeatures());
//            }
//        }
        allocateOrderCreateRequest.setFeatures(getFeaturesNew(receiveLogicWareId, deliveryLogicWareId,request));
        Result<AllocateOrderCreateResponse> saveResult = allocateOrderWriteService.createAllocateOrderApi(allocateOrderCreateRequest);
        if(!saveResult.isSuccess()){
            log.error("createAllocateOrder.BetweenWarehouse,result={}", JSON.toJSONString(saveResult));
            throw new FacadeException(saveResult.getErrorCode(), saveResult.getMessage());
        }
        AllocateOrderCreateResponse result = saveResult.getResult();
        return getAllocateOrderCreateResponse(result.getCode(), result.getThirdAllocateOrderId() ,result.getAllocateOrderDetailList());
    }


}
